import re
from flask import Blueprint,request,jsonify
import json
from db import db1
from werkzeug import datastructures
bp_article = Blueprint('article',__name__)

@bp_article.route('/login',methods=['POST','GET'])
def login():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "select * from cuser where username='%s'"%(data['username'])
        res = db1.findone(sql)
        if res:
            if res['password']==data['password']:
                return jsonify({'code':200,'userid':res['id']})
            else:
                return jsonify({'code':10010,'mes':'密码错误'})
        else:
            return jsonify({'code':10110,'mes':'用户不存在'})
    elif request.method=='GET':
        id = request.args.get('id')
        sql = "select * from carticle where id=%d"%(int(id))
        res = db1.findone(sql)
        return jsonify({'code':200,'list':res})
    


@bp_article.route('/comment',methods=['POST','GET'])
def comment():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
 
        sql = "insert into ccomment values(0,%d,%d,'%s')"%(int(data['userid']),int(data['aid']),data['comment'])
        db1.insert(sql)
        return jsonify({'code':200})

    elif request.method=='GET':
        id  = request.args.get('id')
        sql = "select cuser.username,ccomment.comment from ccomment inner join cuser where  ccomment.userid=cuser.id and aid=%d"%(int(id))
        res = db1.findall(sql)
        print(res)
        return jsonify({'code':200,'list':res})
